package com.kexun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kexun.common.utils.DateUtils;
import com.kexun.common.utils.ResponseEntity;
import com.kexun.entity.DO.Department;
import com.kexun.entity.DO.Manage;
import com.kexun.handler.ApiRRException;
import com.kexun.mapper.ManageMapper;
import com.kexun.service.DepartmentService;
import com.kexun.service.ManageService;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ManageServiceImpl extends ServiceImpl<ManageMapper, Manage> implements ManageService {

    @Autowired
    private ManageMapper manageMapper;

    @Autowired
    private DepartmentService departmentService;

    //    http://kexun.iok.la/login
    @Override
    public Manage findByOpenId(String openId) {
        return manageMapper.findByOpenId(openId);
    }

    @Override
    public Manage findByUserName(String username) {
        return manageMapper.findByUserName(username);
    }

    @Override
    public Manage findUserById(int id) {
        return manageMapper.findUserById(id);
    }

    @Override
    public int have(String username) {
        return manageMapper.selectCount(new QueryWrapper<Manage>().eq("manage_name", username));
    }

    @Override
    public int updState(int id, int state) {
        Manage manage = manageMapper.selectById(id);
        manage.setIsLock(state);
        return manageMapper.updateById(manage);
    }

    @Override
    public Manage register(Manage manage) {
        //盐（用户名+随机数）
        String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
        //原密码
        //散列的次数
        int hashIterations = 2;
        //进行散列获取匹配值
        SimpleHash hash = new SimpleHash("md5", manage.getPassword(), manage.getManageName() + salt, hashIterations);
        String encodedPassword = hash.toHex();
        manage.setPassword(encodedPassword);//加密后的密码
        manage.setCreateTime(DateUtils.getDateTime());//创建时间
        manage.setSalt(salt);//salt
        manageMapper.insert(manage);
        return manage;
    }


    @Override
    public int delManage(int id) {
        return manageMapper.deleteById(id);
    }


    @Override
    public IPage<Map<String, Object>> findList(String name, int page, int limit) {
        return manageMapper.findList(new Page<Manage>(page, limit), name);
    }


    @Override
    public List<Manage> findUserByDeptId(int departmentId) {
        List<Department> deptById = departmentService.findDeptById(departmentId);
        ArrayList<Integer> ids = new ArrayList<>();
        for (Department department : deptById) {
            ids.add(department.getDpId());
        }
        QueryWrapper<Manage> manageQueryWrapper = new QueryWrapper<>();
        manageQueryWrapper.in("department_id", ids);
        List<Manage> manages = manageMapper.selectList(manageQueryWrapper);
        return manages;
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword, Manage manage) {
        String salt = manage.getSalt();
        SimpleHash requestHash = new SimpleHash("md5", oldPassword, manage.getManageName() + salt, 2);
        String dataBasePass = manage.getPassword();
        String requestPass = requestHash.toHex();
        if (!dataBasePass.equals(requestPass)) {
            throw new ApiRRException("旧密码错误请重新输入");
        }
        String newPasswordSalt = new SecureRandomNumberGenerator().nextBytes().toHex();
        SimpleHash newPasswordhash = new SimpleHash("md5", newPassword, manage.getManageName() + newPasswordSalt, 2);
        String encodedNewPassword = newPasswordhash.toHex();
        Manage dataManage = getById(manage.getId());
        dataManage.setPassword(encodedNewPassword);
        dataManage.setSalt(newPasswordSalt);
        updateById(dataManage);
    }

}
